import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, List, Select, Popconfirm, Input,Tooltip  } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  storeRelation,
  getRelation,
  updateRelation,
  removeRelation,
  queryRecord,
  getRecordTotal
} from './service';
import styles from '../../../global.less';
import { CloseOutlined } from '@ant-design/icons';
import EditStore from './components/EditStore';
import { money_trans } from '@/utils/utils';
import moment from 'moment';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const { Option } = Select;
const TableList = ({ handleOnchange, id }) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [StoreFormValues, setStoreFormValues] = useState({});
  const [StorePrice, handleStorePrice] = useState(false);
  const [StorePriceIndex, handleStorePriceIndex] = useState();
  const [count, setCount] = useState();
  const actionRef = useRef();
  const [Selected, setSelected] = useState([]);
  const [storeVisible, handleStoreVisible] = useState(false);
  const [recordVisible, handleRecordVisible] = useState(false);
  const [tipValue, handleTips] = useState(' ');
  const [goodsList, setGoodsList] = useState();
  const [storeState, setStoreState] = useState(false);
  // const handleGetStore = async (state) => {
  //   try {
  //     const { data } = await queryStore();
  //     state ? null : transTitle(data);
  //     setStoreArr(data);
  //   } catch (error) {
  //     return false;
  //   }
  // };
  // const findNode = (row, storeList) => {
  //   let list = [];
  //   storeList.forEach((obj) => {
  //     if (obj.id == row.id) {
  //       obj.stock = row.stock;
  //     } else {
  //       if (obj.children) {
  //         let children = this.findNode(row, obj.children);
  //         obj.children = children;
  //       }
  //     }
  //     list.push(obj);
  //   });
  //   return list;
  // };
  const handleGetPostion = (params) => {
    getRelation({ goodsItemId: params }).then((res) => {
      const { code, data } = res;
      if (code === 0) {
        if (data.length > 0){
          data.forEach((item, index) => {
            item.inCount = null;
          });
        }
        data.length > 0
          ? (setSelected( data), setStoreState(true))
          : (message.info('暂无关联店铺!'), setStoreState(false));
      }
    });
    // queryPosition(params).then((res) => {
    //   if (res.data) {
    //     const {
    //       data: { positionStoreList, provinceId, cityId, areaId },
    //     } = res;
    //     if (positionStoreList) {
    //       positionStoreList.map((item, index) => {
    //         item.name = item.storeName;
    //         item.id = item.storeId;
    //         const list = findNode(item, storeArr);
    //         if (index === positionStoreList.length - 1) {
    //           return list;
    //         }
    //       });
    //       const checkList = positionStoreList.map((item) => {
    //         return (item = item.storeId);
    //       });
    //       setStoreArr(positionStoreList);
    //       setChildren(checkList);
    //       setSelected(positionStoreList);
    //     } else {
    //       setStoreArr([]);
    //       setChildren([]);
    //       setSelected([]);
    //     }
    //   } else {
    //     message.info('查询暂无关联信息!');
    //   }
    // });
  };

  const columns = [
    {
      title: '品项名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '属性名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    // {
    //   title: '库存',
    //   hideInSearch: true,
    //   dataIndex: 'count',
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: true,
    //         message: '库存为必填项',
    //       },
    //     ],
    //   },
    // },
    // {
    //   title: '折扣',
    //   hideInSearch: true,
    //   dataIndex: 'discount',
    // },
    // {
    //   title: '是否优惠',
    //   dataIndex: 'isPre',
    //   hideInSearch: true,
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <Select placeholder="请选择是否优惠">
    //         <Option value={true}>是</Option>
    //         <Option value={false}>否</Option>
    //       </Select>
    //     );
    //   },
    // },
    // {
    //   title: '是否促销',
    //   dataIndex: 'isPro',
    //   hideInSearch: true,
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <Select placeholder="请选择是否促销">
    //         <Option value={true}>是</Option>
    //         <Option value={false}>否</Option>
    //       </Select>
    //     );
    //   },
    // },
    // {
    //   title: '优惠价格',
    //   hideInSearch: true,
    //   dataIndex: 'prePrice',
    // },
    {
      title: '成本价',
      dataIndex: 'cost',

    },
    {
      title: '积分价',
      hideInSearch: true,
      dataIndex: 'integralPrice',
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标价为必填项',
          },
        ],
      },
    },
    {
      title: '会员价',
      hideInSearch: true,
      dataIndex: 'memberPrice',
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标价为必填项',
          },
        ],
      },
    },
    {
      title: '标价',
      hideInSearch: true,
      dataIndex: 'price',
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标价为必填项',
          },
        ],
      },
    },
    {
      title: '单位',
      hideInSearch: true,
      dataIndex: 'unit',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单位为必填项',
          },
        ],
      },
    },
    {
      title: '规格',
      hideInSearch: true,
      dataIndex: 'spec',
    },
    {
      title: '起订量',
      hideInSearch: true,
      dataIndex: 'skip',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <Access accessKey={"@updateGoodsItem"}>
              <a
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setStepFormValues(record);
                  handleModalVisible(true);
                }}
              >
                修改
              </a>
              <Divider type="vertical" />

            </Access>
            <Access accessKey={"@deleteGoodsItem"}>
              <Popconfirm
                placement="top"
                title="确定要删除吗?"
                onConfirm={() => {
                  handleRemove(record.id, actionRef);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@joinGoodsItemStore"}>
              <a
                onClick={() => {
                  handleStoreVisible(true);
                  setGoodsList(record);
                  handleGetPostion(record.id);
                }}
              >
                关联店铺
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@goodsItemStoreRecords"}>
              <a
                onClick={() => {
                  handleRecordVisible(true);
                }}
              >
                上库记录
              </a>
            </Access>

          </>
        );
      },
    },
  ];
  const StoreColumns = [
    {
      title: '成本价',
      dataIndex: 'cost',

    },
    {
      title: '会员价',
      dataIndex: 'memberPrice',
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '会员价为必填项',
          },
        ],
      },
    },
    {
      title: '积分价',
      dataIndex: 'integralPrice',
      render: (dom) => {
        return money_trans(dom);
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '积分价为必填项',
          },
        ],
      },
    },
    {
      title: '标价',
      dataIndex: 'price',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '标价为必填项',
          },
        ],
      },
    },
  ];
  const recordColumns = [
    {
      title: '关联店铺',
      dataIndex: 'storeName',
      render: (dom, entity) => {
        return (
          <Tooltip title={tipValue}  onVisibleChange={(e)=>{
            if (e){
                getRecordTotal(entity.goodsItemStoreId).then(resp=>{
                  if (resp){
                    let str = dom+"总进货量："+resp.data;
                    handleTips(str);
                  }
                });
            }
          }} >
            <div className="ellipsis" style={{ float: 'left', maxWidth: '100%' }}>
              <a>{dom}</a>
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '原库存',
      dataIndex: 'oldStock',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '进货量',
      dataIndex: 'inCount',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '成本价',
      dataIndex: 'cost',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '市场价',
      dataIndex: 'price',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '会员价',
      dataIndex: 'memberPrice',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '积分价',
      dataIndex: 'integralPrice',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },

    {
      title: '原公司库存',
      dataIndex: 'oldCompanyStock',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },

    {
      title: '公司库存上库量',
      dataIndex: 'inCompanyCount',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },

    {
      title: '公司库存',
      dataIndex: 'companyStock',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },

    {
      title: '公司成本价',
      dataIndex: 'companyCost',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '价格类型',
      dataIndex: 'priceType',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '授权价',
          status: 'Processing',
        },
        2: {
          text: '店铺价',
          status: 'Error',
        },
      },
    },
    {
      title: '结算周期',
      dataIndex: 'cycleType',
      hideInSearch: true,
      valueEnum: {
        3: {
          text: '周结',
          status: 'Processing',
        },
        4: {
          text: '月结',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作人',
      dataIndex: 'name',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{dom}</div>;
      },
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (dom, entity) => {
        return <div>{moment(dom).format("YYYY-MM-DD HH:mm:ss")}</div>;
      },
    },
  ];
  const handleSelected = (payload) => {
    const arr = JSON.parse(JSON.stringify(Selected));
    const { goodsId, id, name } = goodsList;

    if (arr.length > 0) {
      let length = 0;
      arr.map((item) => {
        return item.storeId === payload[0].id ? (length += 1) : null;
      });

      length === 0
        ? payload.map((item_) => {
            let list = {
              goodsId: goodsId,
              goodsItemId: id,
              goodsItemName: name,
              stock: item_.stock,
              saleCount: item_.saleCount,
              storeId: item_.id,
              storeName: item_.name,
              state: 1,
            };
            arr.push(list);
          })
        : message.info('已关联该店铺');
    } else {
      payload.map((item_) => {
        let list = {
          goodsId: goodsId,
          goodsItemId: id,
          goodsItemName: name,
          stock: item_.stock,
          saleCount: item_.saleCount,
          storeId: item_.id,
          storeName: item_.name,
          state: 1,
        };
        arr.push(list);
      });
    }
    // payload.map((item_) => {
    //   let list = {
    //     goodsId: goodsId,
    //     goodsItemId: id,
    //     goodsItemName: name,
    //     stock: item_.stock,
    //     storeId: item_.id,
    //     storeName: item_.name,
    //     state: 1,
    //   };
    //   arr.length > 0
    //     ? arr.map((item) => {
    //         return item.storeId === item_.storeId ? message.info('已关联该店铺') : arr.push(list);
    //       })
    //     : arr.push(list);
    // });
    setSelected(arr);
  };
  const handleOk = () => {
    const stateList = Selected.filter((item) => {
      return item.inCount !== undefined && item.inCount !== '';
    });
    const { cost,price, memberPrice, integralPrice } = goodsList;
    Selected.map((item) => {
      (item.saleCount === '') | (item.saleCount === undefined) ? (item.saleCount = 0) : null;
      // (item.cost === '') | (item.cost === undefined) ? (item.cost = 0) : null;
      (item.inCount === '') | (item.inCount === undefined) ? (item.inCount = 0) : null;
      item.priceType === 1
        ? ((item.price = price),
          (item.cost = cost),
          (item.memberPrice = memberPrice),
          (item.integralPrice = integralPrice))
        : null;
      return delete item.state;
    });
    stateList.length === Selected.length
      ? (storeState ? updateRelation(Selected) : storeRelation(Selected))
          .then((res) => {
            const { code } = res;
            code === 0
              ? (message.success('关联成功!'), handleStoreVisible(false))
              : message.error(res.message);
          })
          .catch((err) => {
            console.log(err);
          })
      : message.info('还有未输入的店铺进货量');
  };
  return (
    <div style={{ width: '100%' }}>
      <ProTable
        headerTitle="品项列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleUpdateModalVisible(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter }, id)}
        postData={(payload) => {
          if (handleOnchange) {
            handleOnchange(payload);
          }
          return payload||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
        }}
        columns={columns}
      />
      <CreateForm
        width={1400}
        title={'关联店铺'}
        onCancel={() => {
          handleStoreVisible(false);
          setSelected([]);
        }}
        modalVisible={storeVisible}
        onOk={handleOk}
      >
        <div className="store_div">
          {/* <EditTableStore
            dataSource={storeArr}
            onSelect={StoreSelect}
            handleChildren={children}
            childrenCommission={handleCommissionChild}
            searchState={searchStateFun}
            CommissionState={false}
            handleChild={handleChild}
          /> */}
          <EditStore onSelect={handleSelected} />
          <List
            size="small"
            style={{ width: '60%' }}
            header={<div>关联的店铺</div>}
            footer={null}
            bordered
            dataSource={Selected}
            className={styles.Select_store}
            renderItem={(item, index) => (
              <List.Item key={index}>
                <div className={styles.selected_div}>
                  <div>
                    <span>{item.storeName}</span>
                    <Popconfirm
                      title="确定删除该店铺吗?"
                      onConfirm={() => {
                        const list = JSON.parse(JSON.stringify(Selected));
                        if (item.state === 1) {
                          list.map((item_) => {
                            if (item_.storeId === item.storeId) {
                              return list.splice(index, 1);
                            }
                          });
                          setSelected(list);
                        } else {
                          removeRelation(item.id)
                            .then((res) => {
                              const { code } = res;
                              if (code === 0) {
                                message.success('删除成功!');
                                list.map((item_, index) => {
                                  if (item.storeId === item_.storeId) {
                                    return list.splice(index, 1);
                                  }
                                });
                                list.length === 0 ? setStoreState(false) : null;
                                setSelected(list);
                              } else {
                                message.error(res.message);
                              }
                            })
                            .catch((err) => {
                              console.log(err);
                            });
                        }
                      }}
                      okText="是"
                      cancelText="否"
                    >
                      <CloseOutlined
                        style={{ color: 'red', cursor: 'pointer' }}
                        title={'删除关联'}
                      />
                    </Popconfirm>
                  </div>
                  <div
                    style={{
                      width: '80%',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}
                  >
                    <div>
                      库存：
                      <Input
                        style={{ width: 120 }}
                        value={item.stock}
                        disabled={true}
                      />
                    </div>
                    <div>
                      进货量:
                      <Input
                        style={{
                          width: 110,
                          marginLeft:'10px'
                        }}
                        value={item.inCount}
                        onChange={(val) => {
                          const list = JSON.parse(JSON.stringify(Selected));
                          list[index].inCount = val.target.value;

                          return setSelected(list);
                        }}
                        placeholder="请输入进货量"
                      />
                    </div>
                    {/*<div>*/}
                    {/*  销量:*/}
                    {/*  <Input*/}
                    {/*    style={{ width: 80 }}*/}
                    {/*    value={item.saleCount}*/}
                    {/*    disabled={true}*/}
                    {/*    onChange={(val) => {*/}
                    {/*      const list = JSON.parse(JSON.stringify(Selected));*/}

                    {/*      list[index].saleCount = val.target.value;*/}

                    {/*      return setSelected(list);*/}
                    {/*    }}*/}
                    {/*    placeholder="请输入销量"*/}
                    {/*  />*/}
                    {/*</div>*/}
                    {/* <div>
                      成本价:
                      <Input
                        style={{ width: 80 }}
                        value={item.cost}
                        onChange={(val) => {
                          const list = JSON.parse(JSON.stringify(Selected));
                          list[index].cost = val.target.value;
                          return setSelected(list);
                        }}
                        placeholder="请输入成本"
                      />
                    </div> */}
                    <div>
                      设置授权:{' '}
                      <Select
                        style={{
                          width: 100,
                          marginLeft:'5px'
                        }}
                        defaultValue={
                          item.priceType === 1 ? '授权价格' : item.priceType === 2 ? '店铺价格' : ''
                        }
                        placeholder="选择授权"
                        onChange={(e) => {
                          const list = JSON.parse(JSON.stringify(Selected));
                          if (e === 2) {
                            handleStorePrice(true);
                            handleStorePriceIndex(index);
                            setStoreFormValues(item);
                          }
                          list[index].priceType = e;
                          return setSelected(list);
                        }}
                      >
                        <Option value={1}>授权价格</Option>
                        <Option value={2}>店铺价格</Option>
                      </Select>
                    </div>
                    <div>
                      结算周期:{' '}
                      <Select
                        style={{
                          width: 100,
                          marginLeft:'5px'
                        }}
                        defaultValue={
                          item.cycleType === 3 ? '周结' :  (item.cycleType === 4?'月结':'其他')
                        }
                        placeholder="选择类型"
                        onChange={(e) => {
                          const list = JSON.parse(JSON.stringify(Selected));
                          list[index].cycleType = e;
                          return setSelected(list);
                        }}
                      >
                        <Option value={3}>周结</Option>
                        <Option value={4}>月结</Option>
                        <Option value={5}>其他</Option>
                      </Select>
                    </div>
                  </div>
                </div>
              </List.Item>
            )}
          />
        </div>
      </CreateForm>
      <CreateForm
        width={600}
        title={'店铺售价设置'}
        onCancel={() => handleStorePrice(false)}
        modalVisible={StorePrice}
        footer={null}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            const list = JSON.parse(JSON.stringify(Selected));
            value.cost ? null : (value.cost = 0);
            Object.assign(list[StorePriceIndex], value);
            handleStorePrice(false);
            return setSelected(list);
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: StoreFormValues ? StoreFormValues : null,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={StoreColumns}
        />
      </CreateForm>
      <CreateForm
        width={800}
        title={updateModalVisible ? '修改品项' : '新建品项'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        footer={null}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            updateModalVisible ? (value.id = stepFormValues.id) : null;
            value.goodsId = id;
            value.sort = 0;
            value.cost?null:value.cost=0;
            const success = updateModalVisible
              ? await handleUpdate([value])
              : await handleAdd([value]);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updateModalVisible === true ? stepFormValues : null,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        width={1200}
        title={'上库记录'}
        onCancel={() => {
          handleRecordVisible(false);
        }}
        modalVisible={recordVisible}
      >
        <ProTable
          rowKey="id"
          bordered
          search={{
            labelWidth: 120,
          }}
          request={(params, sorter, filter) => queryRecord({ ...params, sorter, filter }, id)}
          postData={(payload) => {
            const { list, total } = payload;
            setCount(total);
            return list||[];
          }}
          pagination={{
            defaultPageSize: 10,
            total: count,
          }}
          columns={recordColumns}
        />
      </CreateForm>
    </div>
  );
};

export default TableList;
